import React, { useEffect, useRef, useState } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  // Select,
  DatePicker,
  Table,
  Tag,
  Space,
} from 'antd';
import { Link } from 'react-router-dom';
import { getArticleList, deleteArticles } from 'api/channel';
import defaultImg from 'assets/error.png';
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import confirm from 'antd/lib/modal/confirm';
import Channel from './../../components/channel';
import history from 'utils/history';

export default function ArticleList() {
  // const [channels, setChannels] = useState([]);
  // // 获取频道数据问题
  // async function getChannel() {
  //   const res = await getChannels();
  //   // console.log(22, res)
  //   setChannels(res.data.channels);
  // }

  const [articlesData, setArticlesData] = useState({});
  // 获取文章列表
  const getArticleLists = async () => {
    const res = await getArticleList();
    // console.log(36, res);
    setArticlesData(res.data);
  };

  // 1️⃣创建一个 ref 对象，用于存放 params 数据，方便在不同的函数内存值或取值
  const paramsRef = useRef({});
  // 触发表单事件
  const onFinish = async (values) => {
    console.log(values);
    const params = {};
    // 处理状态
    params.status = values.status !== -1 ? values.status : undefined;
    // if (values.status !== -1) {
    //   params.status = values.status;
    // }
    // 处理频道
    if (values.channel_id) {
      params.channel_id = values.channel_id;
    }
    // 处理日期
    if (values.date) {
      params.begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      params.end_pubdate = values.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
    }

    // 统一剔除掉 undefined 的值
    for (const key in params) {
      if (params[key] === undefined) {
        // delete 删除对象的键
        delete params[key];
      }
    }

    // params.page = 1;
    const res = await getArticleList(params);
    console.log(62, res);
    paramsRef.current = params;
    // 渲染数据
    setArticlesData(res.data);
  };

  //每页大小 或者 页码 改变时，触发的事件
  const changePage = async (page, per_page) => {
    const res = await getArticleList({ ...paramsRef.current, page, per_page });
    console.log(50, res);
    setArticlesData(res.data);
  };

  // 删除功能
  const handleDelete = (id) => {
    // console.log(id);
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除吗',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        // 删除请求
        await deleteArticles(id);
        // 重新渲染

        const res = await getArticleList({
          ...paramsRef.current,
          page: articlesData.page,
          per_page: articlesData.per_page,
        });
        setArticlesData(res.data);
      },
    });
  };

  // 编辑功能
  const handleEdit = (id) => {
    // 获取id，两种方式
    // 第一种：这种方式(直接引入history)需要后面解构id才可以拿到id
    // 第二种：，接收proprs，在点击按钮上通过props.history.push(`/edit/${id}`)跳转，通过props.match.params.id获取
    history.push(`/edit/${id}`, { id });
    console.log(119, id);
  };

  useEffect(() => {
    // getChannel();
    getArticleLists();
  }, []);
  // const { Option } = Select;
  const { RangePicker } = DatePicker;

  // 表格框架
  const columns = [
    {
      title: '封面',
      render(item) {
        // console.log(139, item);
        return (
          <img
            src={item.cover.type === 0 ? defaultImg : item.cover.images[0]}
            title={item.title}
            alt={item.title}
            style={{ width: 100, height: 60, objectFit: 'cover' }}
          />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        const tagInfo = articleStatus.find((item) => item.id === status);
        return <Tag color={tagInfo.color}>{tagInfo.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render(value, item) {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => handleEdit(item.id)}
            ></Button>
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(item.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];

  // 状态处理
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  return (
    <div
      className="articleList"
      style={{
        padding: 24,
        height: 'calc(100vh - 64px)',
        overflow: 'auto',
      }}
    >
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单内容 */}
        <Form onFinish={onFinish} initialValues={{ status: -1 }}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            {/* <Select placeholder="请选择频道" style={{ width: 200 }}>
              {channels.map((item) => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select> */}

            <Channel allowClear></Channel>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <div className="articleList">
          <Card title={`根据筛选条件共查询到${articlesData.total_count}条数据`}>
            <Table
              dataSource={articlesData.results}
              columns={columns}
              rowKey="id"
              pagination={{
                position: ['bottomCenter'],
                current: articlesData.page,
                pageSize: articlesData.per_page,
                total: articlesData.total_count,
                // 每页大小 或者 页码 改变时，触发的事件
                onChange: changePage,
              }}
            />
          </Card>
        </div>
      </Card>
    </div>
  );
}
